package top.kaoshanji.p1ch03a;

import top.kaoshanji.u1constant.FileConstant;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

/**
 * 代码清单 p1ch03a-01：使用BufferedInputStream类进行流复用的示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/5 18:42
 */
public class InputStreamExample01 {

    private InputStream input;

    public InputStreamExample01(InputStream input) {
        if (!input.markSupported()) {
            this.input = new BufferedInputStream(input);
        } else {
            this.input = input;
        }
    }

    public InputStream getInputStream() {
        input.mark(Integer.MAX_VALUE);
        return input;
    }

    public void markUsed() throws IOException {
        input.reset();
    }

    public void useStream(InputStream input) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        ReadableByteChannel channel = Channels.newChannel(input);
        int count = 0;
        try {
            count = channel.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(count);
    }

    public static void main(String[] args) throws IOException {

        // 需要新建这个文件，然后，再里面写一点东西（任何内容都行）
        FileInputStream input = new FileInputStream(FileConstant.LOCAL_ROOT_PATH.concat("p1ch03a01.txt"));

        InputStreamExample01 sr = new InputStreamExample01(input);
        InputStream reusable = sr.getInputStream();

        sr.useStream(reusable);
        sr.markUsed();

        reusable = sr.getInputStream();
        sr.useStream(reusable);

    }

}
